package cn.edu.ahtcm.servlet;

import cn.edu.ahtcm.bean.Article;
import cn.edu.ahtcm.bean.User;
import cn.edu.ahtcm.mapper.ArticleMapper;
import cn.edu.ahtcm.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/ArticleAddServlet")
public class ArticleAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String title = req.getParameter("title");
        String content = req.getParameter("content");


        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);


        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        ArticleMapper articleMapper = sqlSession.getMapper(ArticleMapper.class);
        Article article1 = articleMapper.selectByTitle(title);


        if (article1 == null) {
            articleMapper.addArticle(article);
            sqlSession.commit();
            resp.sendRedirect("/admin/manager.jsp");
            sqlSession.close();
        } else {
            req.setAttribute("error", "文章添加失败");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
